# $Id: mkbzlist2.tcl 40 2007-08-31 00:11:58Z khomoutov $
# Makes files.xml.bz2 filelist for a given share.

package require sqlite3
package require tdom

variable options
array set options {
	dbfile    ./scratch.db
	filelist  files.xml.bz2
}

proc dump share {
	variable options

	sqlite3 db $options(dbfile)

	dom createDocument FileListing doc
	set root [$doc documentElement]
	$root setAttribute \
		Version    1 \
		CID        GABBAHEY \
		Base       / \
		Generator  "IncrDC 0.1"

	set node [XMLizeDir $doc $root $share]
	TraverseDir $share $doc $node ""

	file delete $options(filelist)
	set fd [open "| bzip2 -c9 >$options(filelist)" w]
	fconfigure $fd -translation binary

	puts $fd {<?xml version="1.0" encoding="utf-8" standalone="yes"?>}
	$root asXML -channel $fd -indent 1
	close $fd
}

proc TraverseShare {share args} {
	set precmd  ""
	set dircmd  ""
	set filecmd ""
	set postcmd ""

	foreach {opt val} $args {
		switch -- $opt {
			-precmd -
			-precommand {
				set precmd $val
			}
			-dircmd -
			-dircommand {
				set dircmd $val
			}
			-filecmd -
			-filecommand {
				set filecmd $val
			}
			-postcmd -
			-postcommand {
				set postcmd $val
			}
			default {
				return -code error "bad option \"$opt\":\
					must be one of -precommand, -dircommand,\
					-filecommand or -postcommand"
			}
		}
	}

	if {![db exists {select * from shares where name = $share}]} {
		return -code error "share named \"$share\" does not exist"
	}

	db eval {select mtime from shares where name = $share}

	eval $precmd $share

	if {$dircmd ne ""} { eval $dircmd $share $mtime }
	TraverseDir $share ""
}

proc TraverseDir {share parent} {
	db eval {select name from files
			where share = $share and type = 8 and parent = $parent} {
		set node [XMLizeDir $doc $pnode $name]
		TraverseDir $share $doc $node [file join $parent $name]
	}

	db eval {select name, size, TTH from files
			where share = $share and type != 8 and parent = $parent} {
		XMLizeFile $doc $pnode $name $size $TTH
	}
}

proc XMLizeDir {doc pnode name} {
	set node [$pnode appendChild [$doc createElement Directory]]
	$node setAttribute Name $name
	set node
}

proc XMLizeFile {doc pnode name size TTH} {
	set node [$pnode appendChild [$doc createElement File]]
	$node setAttribute Name $name Size $size TTH $TTH
}

set start [clock seconds]
dump dummy
set end [clock seconds]
puts "[expr $end-$start] seconds"

